package com.mradio.app.web;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

@Service(value = "requestInterceptor")
public class RequestInterceptor extends HandlerInterceptorAdapter {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
	    if (localeResolver == null) {
	      throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
	    }

	    Locale locale = localeResolver.resolveLocale(request);
	    LocaleContextHolder.setLocale(locale);
	    request.setAttribute("language", locale.getLanguage());
		return super.preHandle(request, response, handler);
	}

	
}
